package cn.com.chengmandian.sls;

import cn.com.chengmandian.sls.pojo.CommonLogData;
import cn.com.chengmandian.sls.properties.SlsProperties;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.aliyun.log.producer.LogProducer;
import com.aliyun.openservices.aliyun.log.producer.ProducerConfig;
import com.aliyun.openservices.aliyun.log.producer.ProjectConfig;
import com.aliyun.openservices.aliyun.log.producer.errors.ProducerException;
import com.aliyun.openservices.log.common.LogItem;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * <p>
 * sls日志批量写
 * </p>
 *
 * @author dendi
 * @since 2024/9/19
 */
@Slf4j
@Component
public class SlsBatchProducer {

    @Resource
    private SlsProperties slsProperties;

    private LogProducer producer;

    public LogProducer getProducer() {
        if (producer == null) {
            ProducerConfig producerConfig = new ProducerConfig();
            producerConfig.setRetries(3);
            producer = new LogProducer(producerConfig);
            producer.putProjectConfig(new ProjectConfig(slsProperties.getProjectName(), slsProperties.getHost(), slsProperties.getAccessId(), slsProperties.getAccessKey()));
        }
        return producer;
    }

    public void sendLog(CommonLogData logData) throws ProducerException, InterruptedException {
        JSONObject jo = JSONObject.parseObject(logData.toString());
        LogItem logItem = new LogItem();
        for (String key : jo.keySet()) {
            logItem.PushBack(key, jo.getString(key));
        }
        this.getProducer().send(slsProperties.getProjectName(), slsProperties.getCommonLog().getLogStoreName(), logItem);
    }
}
